<?php
/*
Copyright (c) 2010 Samuel Stevens

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
//Database classes require INDEX to be defined, this prevents them being executed on their own
define('INDEX',True);

header('Content-Type: text/plain');

function __autoload($class)
{
	if (file_exists($class.".php"))
		include($class.".php");
}

$config = array(
	'Enabled'   => True,
	'PConnect'  => False,//Optional, use a persistant connection, Default=False
	'Handle'    => Null, //Optional, use existing database connection, uses this instead of connecting again
	'DieOnError'=> True, //Optional, throw exception on query error, Default=True
	'Host'      => 'localhost',
	'Username'  => 'test',
	'Password'  => '',
	'DB'        => 'test'  
	);

$db = new Database($config);

//Create our test tables
//THESE TABLES GET DROPPED AT THE END OF THE SCRIPT (just so you know)
if (!$db->table_exists("table"))
{
	$db->query("CREATE TABLE `table` ( ".
		"`ID` int(11) NOT NULL auto_increment, ".
		"`Text` varchar(255) NOT NULL, ".
		"PRIMARY KEY  (`ID`) ".
		") DEFAULT CHARSET=utf8");
}
$db->query("CREATE TABLE IF NOT EXISTS `table2` ( ".
		"`ID` int(11) NOT NULL auto_increment, ".
		"`tableID` int(11) NOT NULL, ".
		"PRIMARY KEY  (`ID`) ".
		") DEFAULT CHARSET=utf8");

$result = $db->query("Select * From `table`");
//Query accepts 2 more optional parameters
// 2. return array - to automatically extract an associative array rather than a mysql resource (default=True)
// 3. collapse single results - returns a single record instead of result set for singlular results, (default=True)
$fieldsArray = $db->list_fields("table");

//Insert test data
$db->query("Insert Into `table` Set `Text` = 'text123'");
$db->query("Insert Into `table` Set `Text` = '123text'");
$db->query("Insert Into `table2` Set `tableID` = ".$db->last_insert_id());
/*
	Database also provides:
	- list_tables()
	- affected_rows()
	- &get_query_count()
	- get_last_error()
	- last_insert_id()
*/

//Set the database used by all AutoDB instances.
AutoDB::SetDB($db);

/* ######### AutoDB
*/

//Optional second parameter to specify primary key
//If not given, will execute: Show Columns From `$tableName` Where `Key` = 'PRI'
$table = new AutoDB('table'); // new AutoDB('table','ID');

//Single records can be retrieved by primary key
$record = $table->Get(1);

//Simple where clauses can be executed
$records = $table->GetWhere("`Text` Like '%text'","Text Desc"); //optional ordering

/*  And the magic
	Moderatly complex select queries can be created with chained function calls and can be in any order
	
	Available : Where/OrWhere/OrLike/OrNotLike/NotLike/OrderBy/Limit/Join/JoinOn/Select
*/
$records = $table->Select('ID,Text')->Like('Text','%text')->Get(); // or ->Run(), Get() is equivalent to Get(False)

$theQuery;
//Run() allows a parameter to be passed by reference which is set to the generated query string
$records = $table->Select('table.*, table2.ID as table2ID')->Join('table2','table.ID = table2.tableID','Inner')->Like('Text','123%')->Run($theQuery);
echo "Join query: $theQuery\n";
var_dump($records->AsArray());

//GenerateQuery() will construct the query string, with an optional parameter to reset the state

$query = $table->Select('ID,Text')->Like('Text','%text')->GenerateQuery();
echo "Like query: $query\n";
//You can cache this if you like and just run:
$results = $table->Query($query); //Returns resultset/record
var_dump($results->AsArray());

echo "Record count: \n";
var_dump($table->Select('Count(*) as Count')->Run()->AsArray());

/*  ######### Backticks
	All field names are automatically `backticked` to avoid conflicts with language keywords
	Optional, generally there is a parameter to turn it off.
	Backticks for joins are only used if its in the form of "table1.field = table2.field"
*/


/*  ######### AutoDBResultSet
	
	All results (except where collapsed into one record), return a result set.
	While an object, it implements ArrayAccess, Iterator and Countable
*/

$records = $table->Select('ID,Text')->Like('Text','%text')->Get();

echo "Printing result set:\n";
foreach($records as $record)
{
	echo $record->ID.$record['Text']."\n";
} 
for($i=0; $i < count($records); $i++)
{
	echo $records[$i]->ID.$records[$i]['Text']."\n";
}


/*  ######### AutoDBRecord
	Records can be accessed by field or named array
	
	Handles inserting and updating
	Only modifies fields that have changed since the last save
	
	Fields are automatically escaped with db_escape (which calls mysql_real_escape_string)
	This is optional, call $record->Set($field,$value,False) to not use escaping
*/

$record = $records[0];

//Defaults can be used if the field is not set
$field = $record->Get('NOTTHERE','RLY?');

$record->Text .= "OMGOMGOMG";
$record->Save(); //Runs an update, returns True/False

$record = $table->Create();
$record->Text = "NEW";
//Equivalent to:
$record->Set('Text','New');
$id = $record->Save(); //Runs an insert, returns the inserted id

$record->Delete(); //Returns True/False
//OR
$table->Delete($id);

//Records can be resaved once deleted, ie.

$record->Save(); //Inserts it again

$db->query("Drop Table `table`, `table2`");